var VSHADER_SOURCE =
  'attribute vec4 a_Position;\n' +
  'attribute float a_PointSize;\n' +
  'void main() {\n' +
  '  gl_Position = a_Position;\n' +
  '  gl_PointSize = a_PointSize;\n' +
  '}\n';

// Fragment shader program
var FSHADER_SOURCE =
  'void main() {\n' +
  '  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
  '}\n';

var canvas = document.getElementById('example');
var gl = getWebGLContext(canvas);

function clear() {
  // Specify the color for clearing <canvas>
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  // Clear <canvas>
  gl.clear(gl.COLOR_BUFFER_BIT);
}

function initVertexBuffers(gl) {
  var verticesSizes = new Float32Array([
    // Coordinate and size of points
    // 0.5, 0.6, 0.50,
    0.0, 0.5,-0.5, 10.0, // the 1st point
    -0.5, -0.5,0.5, 20.0, // the 2nd point
    // 0.5, -0.5, 30.0, // the 3rd point
  ]);
  var n = 3; // The number of vertices
  // Create a buffer object
  var vertexSizeBuffer = gl.createBuffer();
  if (!vertexSizeBuffer) {
    console.log('Failed to create the buffer object');
    return -1;
  }

  // Bind the buffer object to target
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexSizeBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, verticesSizes, gl.STATIC_DRAW);

  var FSIZE = verticesSizes.BYTES_PER_ELEMENT;
  var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, FSIZE *4,FSIZE * 1);
  gl.enableVertexAttribArray(a_Position); // Enable the assignment of the buffer object

  var a_PointSize = gl.getAttribLocation(gl.program, 'a_PointSize');
  gl.vertexAttribPointer(a_PointSize, 1, gl.FLOAT, false,FSIZE * 4, FSIZE * 3);
  gl.enableVertexAttribArray(a_PointSize); // Enable buffer allocation
  return n;
}



function init() {
  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }

  if (initVertexBuffers(gl) < 0) {
    console.log('Failed to set the positions of the vertices');
    return;
  }
  clear();
  // Draw three points
}

var ang = 0.0;

function animate() {
  requestAnimationFrame(_ => {
    var xformMatrix = new Matrix4();
    var u_xformMatrix = gl.getUniformLocation(gl.program, 'u_xformMatrix');
    var tx = 0.8,
      ty = 0.0;
    var sx = sy = 0.2,
      sz = 1
    clear();
    ang += 0.5
    xformMatrix.setTranslate(tx, ty, 0);
    xformMatrix.scale(sx, sy, sz);
    xformMatrix.rotate(ang, 0, 0, 1);
    gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix.elements);
    gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
    animate();
  })
}

function main() {
  init();
  gl.drawArrays(gl.POINTS, 0, 2);
}